import React, { FC, useState, memo, useCallback } from 'react';
import { List, Calendar, Picker, Button, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import { history } from 'umi';
import { ISearchProps, ISearchQueryProps } from '@/interface';

const Search: FC<ISearchProps> = props => {
  const [selectedCity, setSelectedCity] = useState(['10001']);
  const [timeShow, setTimeShow] = useState(false);
  const [times, setTimes] = useState('');

  const handleCityChange = useCallback((val: any) => {
    if (val) {
      setSelectedCity(val);
    }
  }, []);

  const handleTimeClick = useCallback(() => {
    setTimeShow(!timeShow);
  }, [timeShow]);

  const handleTimeConfirm = useCallback(
    (startTime?: Date, endTime?: Date) => {
      setTimeShow(!timeShow);
      if (startTime && endTime) {
        setTimes(
          dayjs(startTime).format('YYYY-MM-DD') +
            '~' +
            dayjs(endTime).format('YYYY-MM-DD'),
        );
      } else {
        setTimes('');
      }
    },
    [timeShow],
  );

  const handleSearchClick = () => {
    let query: ISearchQueryProps = {};
    if (selectedCity) {
      query.code = selectedCity;
    }
    if (times.includes('~')) {
      const [startTime, endTime] = times.split('~');
      if (startTime && endTime) {
        query.startTime = startTime;
        query.endTime = endTime;
      }

      history.push({
        pathname: '/search',
        query,
      });
    } else {
      Toast.fail('请选择出租时间');
    }
  };

  return (
    <div className="search-wrap">
      <div className="search-wrap_addr">
        {!props.citysLoading && props.citys && (
          <Picker
            title="城市"
            data={props.citys}
            value={selectedCity}
            cascade={false}
            cols={1}
            onChange={handleCityChange}
          >
            <List.Item>可选城市</List.Item>
          </Picker>
        )}
      </div>
      <div className="search-wrap_time" onClick={handleTimeClick}>
        <span className="search-wrap_time_left">出租时间</span>
        <span className="search-wrap_time_right">{times || '可选时间'}</span>
      </div>
      <Button type="warning" onClick={handleSearchClick}>
        搜索民宿
      </Button>
      <Calendar
        visible={timeShow}
        onCancel={handleTimeClick}
        onConfirm={handleTimeConfirm}
      />
    </div>
  );
};

export default memo(Search);
